import { pointApi } from '@/api'

export interface Point {
  id: number
  parentId: number
  pointName: string
  pointCode?: string
  pointFullName?: string
  children?: Point[] | null
}

export function usePointTree() {
  const { vLoading, withLoading } = useDefineLoading()

  const treeData = shallowRef<Point[]>([])

  const getTreeData = async (
    needFullName: 0 | 1 = 1,
    callback?: (o: Point[]) => any,
  ) => {
    try {
      const { data } = await withLoading(
        pointApi.loadTreePoint,
      )(needFullName)
      treeData.value = data || []
      await nextTick()
      callback?.(data || [])
    }
    catch (e) {}
  }

  return {
    treeData,

    vLoading,
    getTreeData,
  }
}

export function useTreeFilter(
  key: string = 'label',
  callback?: (val: string) => any,
) {
  const filterTextInput = ref<string>('')

  const filterNode = (value: string, data: any) => {
    if (!value)
      return true
    return data[key].includes(value)
  }

  watch(
    () => filterTextInput.value,
    (val: string) => {
      callback?.(val)
    },
  )
  return {
    filterTextInput,

    filterNode,
  }
}
